package com.yzdmw.toutiao.information_edit;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.yzdmw.toutiao.R;

import java.io.ByteArrayOutputStream;

public class edit_page extends AppCompatActivity {


    CircleImageView circleImageView;
    EditText username;
    EditText intro;
    TextView gender;
    EditText birth;
    EditText region;
    TextView background;
    ConstraintLayout layout;
    Button commit;
    private Bitmap profile = null;
    private BitmapDrawable back;
    private String name;
    private String introduction;
    private String birthday;
    private String local;
    private String[] sexArray = new String[]{"不展示", "女", "男"};// 性别选择
    private int gen = 0;

    public String getName(){return name;}
    public String getIntroduction(){return introduction;}
    public String getBirthday(){return birthday;}
    public String getRegion(){return local;}
    public Bitmap getProfile(){return profile;}
    public BitmapDrawable getBackground(){return back;}
    public int getGender(){return gen;}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_page);
        init_avatar();
        init_gender();
        init_name();
        init_intro();
        init_birth();
        init_region();
        init_background();
        getSupportActionBar().hide();
        commit = findViewById(R.id.commit_button);
        commit.setOnClickListener(view -> {
            new Thread() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    intent.putExtra("name",name);
                    intent.putExtra("introduction",introduction);
                    intent.putExtra("birthday",birthday);
                    intent.putExtra("local",local);
                    intent.putExtra("gen",gen);
                    if(profile != null) {
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        profile.compress(Bitmap.CompressFormat.JPEG,100, baos);
                        int options = 100;
                        while (baos.toByteArray().length / 1024 > 100) {  //循环判断如果压缩后图片是否大于100kb,大于继续压缩
                            baos.reset();//重置baos即清空baos
                            profile.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
                            options -= 10;//每次都减少10
                        }
                        byte[] byteArray = baos.toByteArray();
                        intent.putExtra("profile",byteArray);
                    }
                    else {
                        intent.putExtra("profile","");
                    }
                    setResult(23,intent);
                    finish();
                }
            }.start();
        });
    }

    public void init_avatar(){
        circleImageView = findViewById(R.id.avatar);
        circleImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS,//联系人的权限
                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        }
                        else{
                            System.out.println("YES!");
                        }
                    }
                }
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            System.out.println(picturePath);
            profile = BitmapFactory.decodeFile(picturePath);
            circleImageView.setImageBitmap(profile);
        } else if(requestCode == 2 && resultCode == RESULT_OK && null != data){
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            System.out.println(picturePath);
            Bitmap bp = BitmapFactory.decodeFile(picturePath);
            back = new BitmapDrawable(bp);
            layout.setBackground(back);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public void init_gender(){
        gender = findViewById(R.id.gender_state);
        gender.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
        gender.getPaint().setAntiAlias(true);//抗锯齿
        gender.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder3 = new AlertDialog.Builder(edit_page.this);// 自定义对话框
                builder3.setSingleChoiceItems(sexArray, gen, new DialogInterface.OnClickListener() {// 2默认的选中

                    @Override
                    public void onClick(DialogInterface dialog, int which) {// which是被选中的位置
                        // showToast(which+"");
                        gender.setText(sexArray[which]);
                        gen = which;
                        dialog.dismiss();// 随便点击一个item消失对话框，不用点击确认取消
                    }
                });
                builder3.show();// 让弹出框显示
            }
        });
    }

    public void init_name(){
        username = findViewById(R.id.username_state);
        username.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                name = s.toString();
                System.out.println(name);
            }
        });
    }

    public void init_intro(){
        intro = findViewById(R.id.intro_state);
        intro.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                introduction = s.toString();
                System.out.println(introduction);
            }
        });
    }

    public void init_birth(){
        birth = findViewById(R.id.birth_state);
        birth.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                birthday = s.toString();
                System.out.println(birthday);
            }
        });
    }

    public void init_region(){
        region = findViewById(R.id.region_state);
        region.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                local = s.toString();
                System.out.println(local);
            }
        });
    }

    public void init_background(){
        layout = findViewById(R.id.layout);
        background = findViewById(R.id.background_state);
        background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    int REQUEST_CODE_CONTACT = 101;
                    String[] permissions = {Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS,//联系人的权限
                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};//读写SD卡权限
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            requestPermissions(permissions, REQUEST_CODE_CONTACT);
                        }
                        else{
                            System.out.println("YES!");
                        }
                    }
                }
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
            }
        });
    }
}